package com.okilo.online.app.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Typeface
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import com.okilo.online.app.OkiloApplication
import com.okilo.online.app.R
import com.okilo.online.app.common.OkiloComDlog
import com.okilo.online.app.databinding.OkiloDlogCServiceBinding
import com.okilo.online.app.databinding.OkiloDlogCServiceItemBinding
import com.okilo.online.app.event.OkiloEventPointType
import com.okilo.online.app.tools.OkiloDensityUtil
import com.okilo.online.app.tools.helper.OkiloConfigCustomerHp
import com.okilo.online.app.tools.shared.OkiloSharedHp
import com.okilo.online.app.tools.shared.OkiloSharedKey
import com.okilo.online.app.tools.apt.OkiloOnSingleClickListener
import org.json.JSONObject

/**
 * OkiloLoan
 * @Author wwdeng
 * @CreateTime: 2024/11/15 10:29
 * @Annotation：联系客服Dialog
 */
class OkiloCServiceDlog(context: Context) : OkiloComDlog(context) {
    lateinit var binding: OkiloDlogCServiceBinding
    private var callback: ICServiceDlogCallback? = null

    override val dialogName: String = "Customer_Service"

    override fun initializeOkiloWindow() {
        val params = window?.attributes
        params?.width = OkiloApplication.app.getPhoneWidth() - OkiloDensityUtil.dp2px(32f)
        params?.height = WindowManager.LayoutParams.WRAP_CONTENT
        window?.attributes = params
        window?.setWindowAnimations(R.style.dialog_slide_anim) //修改动画样式
        window?.setGravity(Gravity.CENTER)
    }

    override fun createOkiloContentView(): View {
        binding = OkiloDlogCServiceBinding.inflate(LayoutInflater.from(context))
        return binding.root
    }

    override fun initializeOkiloViews() {
    }

    override fun setupOkiloEventListeners() {
        setOnClickListener(binding.okiloCServiceCloseIcon)
        setOnClickListener(binding.okiloCServiceButtonFeedback)
    }

    override fun loadOkiloData() {
        val isLogin = OkiloSharedHp.gOkiloSharedBoolean(OkiloSharedKey.SP_OKILO_LOGIN)
        if (isLogin){
            binding.okiloCServiceButtonFeedback.visibility = View.VISIBLE
        } else {
            binding.okiloCServiceButtonFeedback.visibility = View.GONE
        }
        sOkiloCustomerContactDataList()
    }

    override fun onOkiloEventViewClick(v: View?) {
        dismiss()
        when(v?.id){
            R.id.okiloCServiceCloseIcon -> {
                addEventPointRequestAction(OkiloEventPointType.OKILO_CLICK_TRACK.CUSTOMER_CLOSE)
            }
            R.id.okiloCServiceButtonFeedback -> {
                addEventPointRequestAction(OkiloEventPointType.OKILO_CLICK_TRACK.CUSTOMER_FEEDBACK)
                callback?.onOkiloCServiceFeedbackClick()
            }
        }
    }

    /**
     * 事件备注
     */
    fun sOkiloCServiceEventRemark(remark: String): OkiloCServiceDlog {
        dialogRemark = remark
        return this
    }

    /**
     * 设置监听回调
     */
    fun sOkiloCServiceClickCallback(callback: ICServiceDlogCallback): OkiloCServiceDlog {
        this.callback = callback
        return this
    }

    /**
     * 获取联系方式列表
     */
    @SuppressLint("SetTextI18n")
    private fun sOkiloCustomerContactDataList(){
        binding.okiloCServiceWorkTimeText.visibility = View.VISIBLE
        binding.okiloServiceListLayout.removeAllViews()

        val contactList = arrayListOf<JSONObject>()
        val customize = OkiloConfigCustomerHp.gOkiloConfigCustomerData()
        customize?.let {
            if (it.optString("mobile","").isNotEmpty()){
                val mobileList = it.optString("mobile").split(",")
                for (i in mobileList.indices){
                    val obj = JSONObject()
                    obj.put("type","MOBILE")
                    obj.put("value", mobileList[i])
                    obj.put("isShowTips",i == mobileList.size - 1)
                    contactList.add(obj)
                    sOkiloCustomerServiceItemView(obj)
                }
            }

            if (it.optString("email","").isNotEmpty()){
                val emailList = it.optString("email").split(",")
                for (i in emailList.indices){
                    val obj = JSONObject()
                    obj.put("type","EMAIL")
                    obj.put("value", emailList[i])
                    contactList.add(obj)
                    sOkiloCustomerServiceItemView(obj)
                }
            }
        }

        //工作时间
        sOkiloCustomerServiceTimeText(customize)
    }

    /**
     * 添加联系方式item
     */
    private fun sOkiloCustomerServiceItemView(item: JSONObject){
        val itemBinding = OkiloDlogCServiceItemBinding.inflate(LayoutInflater.from(context))
        itemBinding.textCustomerValue.text = item.optString("value")
        when(item.optString("type")){
            "MOBILE" -> {//电话
                itemBinding.textCustomerTitle.text = getString(R.string.okilo_service_customer_mobile_title)
                itemBinding.textCustomerFun.text = getString(R.string.okilo_service_customer_mobile_dial)
                itemBinding.textCustomerFun.visibility = View.VISIBLE
                itemBinding.textCustomerFun.visibility = View.VISIBLE
            }
            else -> {//邮箱
                itemBinding.textCustomerTitle.text = getString(R.string.okilo_service_customer_email_title)
                itemBinding.textCustomerFun.text = getString(R.string.okilo_service_customer_email_copy)
                itemBinding.textCustomerFun.visibility = View.GONE
            }
        }
        if (item.optBoolean("isShowTips",false)){
            itemBinding.okiloCServicePhoneNumberTipsLayout.visibility = View.VISIBLE
        } else {
            itemBinding.okiloCServicePhoneNumberTipsLayout.visibility = View.GONE
        }
        itemBinding.textCustomerFun.setOnClickListener(object : OkiloOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                when (item.optString("type")) {
                    "MOBILE" -> {//电话
                        addEventPointRequestAction(OkiloEventPointType.OKILO_CLICK_TRACK.CUSTOMER_DIAL, "Mobile ：${item.optString("value")}")
                        callback?.onOkiloCServiceMobileDialClick(item.optString("value"))
                    }
                    else -> {//邮箱

                    }
                }
            }
        })
        binding.okiloServiceListLayout.addView(itemBinding.root)
    }

    /**
     * 设置客服工作时间
     */
    private fun sOkiloCustomerServiceTimeText(data: JSONObject?){
        //客服配置里没有配置工作时间，取主产品的工作时间展示
        var workTime = "Monday to Sunday,9:00am to 6:30pm"
        data?.let {
            val customData = it.optJSONObject("customData")
            if (customData != null){
                if (!customData.has("workDate") || !customData.has("workTime")){
                    val commonCustomData = OkiloConfigCustomerHp.gOkiloConfigCustomerCustomData()
                    if (commonCustomData != null) {
                        customData.put("workDate",commonCustomData.optString("workDate"))
                        customData.put("workTime",commonCustomData.optString("workTime"))
                    }
                }
                workTime = "${customData.optString("workDate")}${customData.optString("workTime")}"
            }
        }

        val showWorkTime = String.format(getString(R.string.okilo_service_customer_time), workTime)
        val workTimeSpannable = SpannableString(showWorkTime)
        val startIndex = showWorkTime.indexOf(workTime)
        workTimeSpannable.setSpan(ForegroundColorSpan(getColor(R.color.okilo_color_ff666666)), startIndex, startIndex + workTime.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        //加粗
        workTimeSpannable.setSpan(StyleSpan(Typeface.BOLD), startIndex, startIndex + workTime.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.okiloCServiceWorkTimeText.text = workTimeSpannable
    }

    interface ICServiceDlogCallback {
        //拨号
        fun onOkiloCServiceMobileDialClick(phoneNumber: String)
        //feedback
        fun onOkiloCServiceFeedbackClick()
    }
}